<!--搜索页面-->
<template>
  <!--顶部搜索栏-->
  <form action="/">
    <van-search
        v-model="searchText"
        show-action
        placeholder="请选择搜索的标签选项"
        @search="onSearch"
        @cancel="onCancel"
    />
  </form>

  <!--分割线-->
  <van-divider content-position="left">
    已选择标签
  </van-divider>

  <!--占位符 - 没有选择标签时显示-->
  <div v-if="activeIds.length === 0" style="text-align: center">当前无选择的标签</div>

  <!--已选择的标签-->
  <!-- 设置垂直间距 -->
  <van-row :gutter="[20, 20]">
    <van-col span="6" v-for="tag in activeIds">
      <van-tag closeable size="small" type="primary" @close="doClose(tag)">
        {{ tag }}}
      </van-tag>
    </van-col>
  </van-row>


  <!--分割线-->
  <van-divider content-position="left">
    选择标签
  </van-divider>

  <!--标签选择器-->
  <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="tagList"
  />

  <!--  根据标签搜索用户-->
  <div style="padding: 4px">
    <van-button block @click="doSearchByTags" type="primary">确认搜索</van-button>
  </div>

</template>

<script setup lang="ts">
import {ref} from 'vue';
import {useRouter} from "vue-router";

const router = useRouter();

// 顶部搜索栏
const searchText = ref('');
const originalTagList = [
  {
    text: '性别',
    children: [
      {text: '男', id: '男'},
      {text: '女', id: '女'},
      {text: '未知', id: '未知'},
    ],
  },
  {
    text: '职业',
    children: [
      {text: '学生', id: '学生'},
      {text: 'java', id: 'java'},
      {text: 'python', id: 'python'},
      {text: 'C++', id: 'C++'},
    ],
  },
];
let tagList = ref(originalTagList);

/**
 * 搜索过滤
 * @param val
 * @returns
 */
const onSearch = (val) => {
  tagList.value = originalTagList.map(parentTag => {
    const tempChildren = [...parentTag.children];
    const tempParentTag = {...parentTag};
    tempParentTag.children = tempChildren.filter(item =>
        item.text.includes(searchText.value));
    return tempParentTag;
  });
};

const onCancel = () => {
  searchText.value = '';
  tagList.value = originalTagList;
}

// 标签选择器
const activeIds = ref([]);
const activeIndex = ref(0);

// 移除标签
const doClose = (tag: string) => {
  activeIds.value = activeIds.value.filter(item =>
      item !== tag);
};

// 根据标签搜索用户
const doSearchByTags = () => {
  router.push({
    path: '/user/list',
    query: {
      tags: activeIds.value,
    },
  });
}

</script>

<style scoped>

</style>